﻿using UnityEngine;
using System.Collections;

public class LevelManager : MonoBehaviour 
{
    public static LevelManager Instance { get; private set; }
    public Player Player { get; private set; }
    public CameraController Camera { get; private set; }
    public int AsteroidsRemaining { get; private set; }
    public Asteroid Asteroid;
    public Bounds LevelBounds;
    public float maxAsteroidSize;


    public void Awake()
    {
        Instance = this;
    }

    public void Start()
    {
        Player = FindObjectOfType<Player>();
        Camera = FindObjectOfType<CameraController>();
        LevelBounds = Camera.CameraBounds.bounds;
        AsteroidsRemaining = Random.Range(1,5);

        for (var i = 0; i <= AsteroidsRemaining; i++)
        {
            var size = Random.Range(.5f, maxAsteroidSize);
            SpawnAsteroid(size);
        }
    }

    private void SpawnAsteroid(float scaleFactor)
    {
        var spawnPosition = new Vector3(
            Random.Range(LevelBounds.min.x, LevelBounds.max.x),
            Random.Range(LevelBounds.min.y, LevelBounds.max.y));
        var asteroid  = (Asteroid) Instantiate(Asteroid, spawnPosition, new Quaternion(0, 0, 0, 0));
        asteroid.transform.localScale += new Vector3(scaleFactor, scaleFactor, 0);
    }

    public void asteroidDestroyed(GameObject asteroid)
    {
        Debug.Log(AsteroidsRemaining.ToString());
        var scaleFactor = asteroid.transform.localScale.x;
        if(scaleFactor >= 1)
        {
            var asteroidToSpawn = (int) (scaleFactor % .5f);
            Debug.Log(string.Format("AsteroidsToSpawn:{0}", asteroidToSpawn));
            scaleFactor /= 2;
            Debug.Log(scaleFactor.ToString());
            if (asteroidToSpawn > 0)
            {
                for (var i = 0; i <= asteroidToSpawn; i++)
                {
                    SpawnAsteroid(scaleFactor);
                }
            }
            AsteroidsRemaining += asteroidToSpawn;
        }
        AsteroidsRemaining -= 1;

        if (AsteroidsRemaining < 0)
        {
            LevelFinished();
        }
    }

    public void LevelFinished()
    {
        Debug.Log("LevelComplete");
    }   

    public void KillPlayer()
    {
        StartCoroutine(KillPlayerCo());
    }

    private IEnumerator KillPlayerCo()
    {
        Player.Kill();
        yield return new WaitForSeconds(2f);
    }
}
